<template>
  <el-card class="shadow-sm">
    <el-button type="primary" @click="dialogVisible=true">新增存储场景</el-button>
    <div class="flex flex-col h-full">
      <el-table :data="sceneList" border stripe fit highlight-current-row>
        <el-table-column label="ID" prop="id" width="80" sortable></el-table-column>
        <el-table-column label="场景标识" prop="sceneCode" width="120"></el-table-column>
        <el-table-column label="存储桶名称" prop="bucketName" width="120"></el-table-column>
        <el-table-column label="路径模板" prop="pathTemplate">
          <template #default="scope">
            <el-tooltip content="查看完整路径模板" placement="top">
              <div class="truncate max-w-[200px]" :title="scope.row.pathTemplate">
                {{ scope.row.pathTemplate }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="允许的文件类型" prop="allowFileTypes">
          <template #default="scope">
            <el-tag
                v-for="type in scope.row.allowFileTypes?.split(',')"
                :key="type"
                size="small"
                effect="plain">
              {{ type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最大文件大小" prop="maxFileSize" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.maxFileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="公共场景" prop="isPublic">
          <template #default="scope">
            <el-tag
                :type="scope.row.isPublic === 1 ? 'success' : 'info'"
                size="small">
              {{ scope.row.isPublic === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="isEnabled"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"  sortable></el-table-column>
        <el-table-column label="过期时间" prop="expireTime" >
          <template #default="scope">
            <el-tag
                :type="isExpired(scope.row.expireTime) ? 'danger' : 'success'"
                size="small"
                v-if="scope.row.expireTime">
              {{ isExpired(scope.row.expireTime) ? '已过期' : '未过期' }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button
                size="small"
                @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
        v-model="dialogVisible"
        title="文件上传场景"
        width="40%"
        @close="handleClose">
      <el-form
          ref="formRef"
          :model="sceneForm"
          :rules="rules"
          label-width="120px"
          class="space-y-4">
        <el-form-item label="场景标识" prop="sceneCode">
          <el-input v-model="sceneForm.sceneCode" placeholder="请输入场景标识"></el-input>
        </el-form-item>
        <el-form-item label="存储桶名称" prop="bucketName">
          <el-input v-model="sceneForm.bucketName" placeholder="请输入存储桶名称"></el-input>
        </el-form-item>
        <el-form-item label="路径模板" prop="pathTemplate">
          <el-input
              v-model="sceneForm.pathTemplate"
              type="textarea"
              :rows="2"
              placeholder="请输入路径模板，支持变量，如avatars/{userId}/"></el-input>
          <div class="text-xs text-gray-500 mt-1">
            支持变量：{date}、{md5} 等
          </div>
        </el-form-item>
        <el-form-item label="允许的文件类型" prop="allowFileTypes">
          <el-input
              v-model="inputType"
              placeholder="请输入允许的文件类型，多个类型用逗号分隔"
              @keyup.enter.native="handleAddFileType">
            <template #append>
              <el-button @click="handleAddFileType">添加</el-button>
            </template>
          </el-input>
          <div class="flex flex-wrap gap-2 mt-2">
            <el-tag
                v-for="(type, index) in fileTypeList"
                :key="index"
                closable
                @close="removeFileType(index)">
              {{ type }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="最大文件大小" prop="maxFileSize">
          <el-input-number
              v-model="sceneForm.maxFileSize"
              :min="1"
              :max="10737418240"
              :step="1048576"
              :precision="0"
              size="small"
              placeholder="请输入最大文件大小"></el-input-number>
          <el-select
              v-model="fileSizeUnit"
              size="small"
              style="width: 80px; margin-left: 5px">
            <el-option label="KB" value="1024"></el-option>
            <el-option label="MB" value="1048576"></el-option>
            <el-option label="GB" value="1073741824"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否为公共场景" prop="isPublic">
          <el-radio-group v-model="sceneForm.isPublic">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="isEnabled">
          <el-radio-group v-model="sceneForm.isEnabled">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="场景说明" prop="remark">
          <el-input
              v-model="sceneForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入场景说明"></el-input>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
              v-model="sceneForm.expireTime"
              type="datetime"
              placeholder="请选择过期时间"
              value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end space-x-3">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {reqCreateScene, reqDeleteScene, reqGetSceneList, reqUpdateScene} from '@/api/file/scene';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import {Edit,Delete} from '@element-plus/icons-vue'
import {ElMessageBox,ElMessage} from "element-plus";

let sceneList = ref([]);
let fileSizeUnit = ref()//文件大小单位
let formRef = ref(null)
let sceneForm = reactive({
  id: null,
  sceneCode: '',
  bucketName: '',
  pathTemplate: '',
  allowFileTypes: '',
  maxFileSize: 10485760, // 默认10MB
  isPublic: 0,
  isEnabled: 1,
  remark: '',
  createTime: '',
  updateTime: '',
  expireTime: ''
})
let inputType = ref('')
let fileTypeList = ref([]);
let dialogVisible = ref(false)
const rules = ref({
  sceneCode: [
    {required: true, message: '请输入场景标识', trigger: 'blur'},
    {min: 2, max: 50, message: '场景标识长度在2到50个字符', trigger: 'blur'}
  ],
  bucketName: [
    {required: true, message: '请输入存储桶名称', trigger: 'blur'},
    {min: 3, max: 63, message: '存储桶名称长度在3到63个字符', trigger: 'blur'}
  ],
  pathTemplate: [
    {required: true, message: '请输入路径模板', trigger: 'blur'}
  ],
  maxFileSize: [
    {required: true, message: '请输入最大文件大小', trigger: 'blur'},
    {type: 'number', message: '最大文件大小必须为数字值', trigger: 'blur'}
  ]
});

let getSceneList = async () => {
  let res = await reqGetSceneList()
  sceneList.value = res.data
}
// 检查是否过期
const isExpired = (expireTime) => {
  if (!expireTime) return false;
  return new Date(expireTime) < new Date();
};

let handleAddFileType = () => {
  fileTypeList.value.push(inputType.value)
  inputType.value = ''
}
let removeFileType = (index) => {
  fileTypeList.value.splice(index, 1)
}
let handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      sceneForm.allowFileTypes = fileTypeList.value.join(',')
      if (sceneForm.id) await reqUpdateScene(sceneForm)
      else await reqCreateScene(sceneForm)
      getSceneList()
      dialogVisible.value = false
    } else {
      console.log('error submit!', fields)
    }
  })
}
let handleEdit = (row) => {
  Object.assign(sceneForm, row)
  fileTypeList.value = row.allowFileTypes?.split(',')
  dialogVisible.value = true
}
let handleDelete=(row)=>{
  ElMessageBox.confirm(
      `删除之后不能恢复，确认删除记录${row.sceneCode}?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      } as string
  )
      .then(() => {
        reqDeleteScene(row.id).then(()=>{
          getSceneList()
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
}
// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

onMounted(() => {
  getSceneList()
})
let handleClose = () => {
  sceneForm.id = null
  sceneForm.sceneCode = ''
  sceneForm.bucketName = ''
  sceneForm.pathTemplate = ''
  sceneForm.allowFileTypes = ''
  sceneForm.maxFileSize = 10485760
  sceneForm.isPublic = 0
  sceneForm.isEnabled = 1
  sceneForm.remark = ''
  sceneForm.createTime = ''
  sceneForm.updateTime = ''
  sceneForm.expireTime = ''
  fileTypeList.value = []
  inputType.value = ''
  fileSizeUnit.value = ''
}
</script>

<style scoped>

</style>
